package com.lining.orangeservice.service.impl;

import com.lining.orangeservice.common.BusinessException;
import com.lining.orangeservice.common.enums.ErrorCode;
import com.lining.orangeservice.entity.po.Permission;
import com.lining.orangeservice.entity.po.Role;
import com.lining.orangeservice.mapper.PermissionMapper;
import com.lining.orangeservice.mapper.RoleMapper;
import com.lining.orangeservice.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void assignPermissionsToRole(Long roleId, List<Long> permissionIds) {

        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new BusinessException(ErrorCode.ROLE_NOT_EXISTS);
        }

        for (Long permissionId : permissionIds){
            if (permissionMapper.selectById(permissionId) == null){
                throw new BusinessException(ErrorCode.PERMISSION_NOT_EXISTS);
            }
        }

        roleMapper.insertRolePermissions(roleId, permissionIds);
    }

    @Override
    public void removePermissionsFromRole(Long roleId, List<Long> permissionIds) {
        permissionMapper.deleteRolePermissions(roleId, permissionIds);
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return permissionMapper.selectByRoleId(roleId);
    }

    @Override
    public List<Permission> getPermissionsByUserId(Long id) {
        return permissionMapper.selectPermissionsByUserId(id);
    }
}
